import { useEffect, useRef } from "react"

type Props = {
    onSwipeRight?: () => void
    onSwipeLeft?: () => void
    isAnimate?: boolean, // 是否加入滑动动画
    threshold?: number
}

// 注册左滑右滑事件
const useTouch = (props: Props) => {
    const ref = useRef<HTMLDivElement>()

    const startX = useRef(0);
    const startY = useRef(0);

    const handleTouchStart = (e) => {
        startX.current = e.touches[0].clientX;
        startY.current = e.touches[0].clientY;
    };
    const handleTouchEnd = (e) => {
        const deltaX = e.changedTouches[0].clientX - startX.current;
        const deltaY = e.changedTouches[0].clientY - startY.current;
        if (Math.abs(deltaX) > Math.abs(deltaY) && deltaX > 0) {
            props.onSwipeRight && props.onSwipeRight()
        } else if (Math.abs(deltaX) > Math.abs(deltaY) && deltaX < 0) {
            props.onSwipeLeft && props.onSwipeLeft()
        }
        if (props.isAnimate) {
            ref.current.style.transition = 'transform 0.3s ease';
            ref.current.style.transform = 'translateX(0)';
        }
    };

    const handleTouchMove = (e) => {
        if (props.isAnimate) {
            const touchEndX = e.touches[0].clientX;
            const deltaX = touchEndX - startX.current;
            const threshold = props.threshold || 16

            if (Math.abs(deltaX) > threshold) {

                ref.current.style.transform = `translateX(${deltaX > 0 ? threshold : -threshold}px)`;
            }

        }
    }

    useEffect(() => {
        const dom = ref.current;
        if (!dom) return
        dom.addEventListener('touchstart', handleTouchStart);
        dom.addEventListener('touchmove', handleTouchMove);
        dom.addEventListener('touchend', handleTouchEnd);

        return () => {
            dom.removeEventListener('touchstart', handleTouchStart);
            dom.removeEventListener('touchmove', handleTouchMove);
            dom.removeEventListener('touchend', handleTouchEnd);
        };
    }, [handleTouchMove])

    return {
        ref
    }
}

export default useTouch